package it.polimi.traveldream.web.beans.customer;

import it.polimi.traveldream.ejbclient.dtos.TravelPackageDTO;
import it.polimi.traveldream.ejbclient.eaos.AccountServiceEAO;
import it.polimi.traveldream.ejbclient.eaos.ParticipationServiceEAO;
import it.polimi.traveldream.utils.exceptions.NotAvailableException;
import it.polimi.traveldream.utils.exceptions.NotSuchProductException;
import it.polimi.traveldream.utils.exceptions.NotSuchUserException;
import it.polimi.traveldream.web.beans.shared.FacesContextHandler;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

@ManagedBean(name="participatePackage")
@RequestScoped
public class ParticipatePackageBean {
	@EJB
	private ParticipationServiceEAO pService;
	@EJB
	private AccountServiceEAO aService;
	@ManagedProperty(value="#{listCustomerTravelPackages.selectedTravelPackage}")
	private TravelPackageDTO travelPackage;
	private int reservations;
	
	public ParticipatePackageBean() {
	}
	
	@PostConstruct
	public void init() {
		reservations = 1;
	}
	
	public TravelPackageDTO getTravelPackage() {
		return travelPackage;
	}

	public void setTravelPackage(TravelPackageDTO travelPackage) {
		this.travelPackage = travelPackage;
	}
	
	public int getReservations() {
		return reservations;
	}

	public void setReservations(int reservations) {
		this.reservations = reservations;
	}

	public String participateTravelPackage() {
		try {
			pService.confirmParticipation(aService.getCurrentUser().getId(), travelPackage.getId(), reservations);
			return "index";
		} catch (NotSuchUserException e) {
			FacesContextHandler.produceFacesMessage("growl",FacesContext.getCurrentInstance(),
					FacesMessage.SEVERITY_ERROR, "User doesn't exist.");
			return "participateTravelPackage";
		} catch (NotAvailableException e) {
			FacesContextHandler.produceFacesMessage("growl",FacesContext.getCurrentInstance(),
					FacesMessage.SEVERITY_ERROR, "The travel package is not available for " + reservations + " reservations.");
			return "participateTravelPackage";
		} catch (NotSuchProductException e) {
			FacesContextHandler.produceFacesMessage("growl",FacesContext.getCurrentInstance(),
					FacesMessage.SEVERITY_ERROR, "The travel package is no more available.");
			return "participateTravelPackage";
		}
	}
	
}
